package com.origin.utils.gson

import android.text.TextUtils
import com.google.gson.Gson
import com.origin.utils.gson.BaseResponse
import com.origin.utils.gson.GsonUtils
import com.origin.utils.gson.GsonUtils.fromJsonObject
import java.lang.Exception
import java.lang.reflect.Type

object GsonUtils {
    var gson = Gson()
    private const val bodyJsonSyntaxException =
        "{\"code\":201,\"data\":null,\"msg\":\"JsonSyntaxException\"}"
    private const val bodyEmpty = "{\"code\":201,\"data\":null,\"msg\":\"bodyEmpty\"}"

    fun Any.toJsonString(): String {
        val gson = Gson()
        return gson.toJson(this)
    }

    fun <T> String.strToJavaBean(classOfT: Class<T>) :T{
        val gson = Gson()
        return gson.fromJson(this, classOfT);
    }

    private fun <T> fromJsonArrayBase(
        reader: String,
        clazz: Class<T>
    ): BaseResponse<MutableList<T>> {
        val gson = Gson()
        // 生成List<T> 中的 List<T>
        val listType: Type =
            ParameterizedTypeImpl(MutableList::class.java, arrayOf<Class<*>>(clazz))
        // 根据List<T>生成完整的Result<List<T>>
        val type: Type = ParameterizedTypeImpl(BaseResponse::class.java, arrayOf(listType))
        return gson.fromJson(reader, type)
    }

    private fun <T> fromJsonObjectBase(reader: String?, clazz: Class<T>): BaseResponse<T> {
        val gson = Gson()
        val type: Type = ParameterizedTypeImpl(
            BaseResponse::class.java, arrayOf<Class<*>>(clazz)
        )
        return gson.fromJson(reader, type)
    }

    fun <T> String.fromJsonObject(clazz: Class<T>): BaseResponse<T> {
        val t: BaseResponse<T>
        if (TextUtils.isEmpty(this)) {
            t = fromJsonObjectBase(bodyEmpty, clazz)
            return t
        }
        t = try {
            fromJsonObjectBase(this, clazz)
        } catch (e: Exception) {
            fromJsonObjectBase(bodyJsonSyntaxException, clazz)
        }
        return t
    }

    fun <T> String.fromJsonArray(clazz: Class<T>): BaseResponse<MutableList<T>> {
        val t: BaseResponse<MutableList<T>>
        if (TextUtils.isEmpty(this)) {
            t = fromJsonArrayBase(bodyEmpty, clazz)
            return t
        }
        t = try {
            fromJsonArrayBase(this, clazz)
        } catch (e: Exception) {
            fromJsonArrayBase(bodyJsonSyntaxException, clazz)
        }
        return t

    }
}